<template>
  <div class="product-list">
    <h1>商品信息</h1>
    <el-table :data="products" style="width: 100%" stripe>
      <el-table-column prop="storeProductId" label="ID" width="100" />
      <el-table-column prop="productName" label="名称" width="180" />
      <el-table-column prop="price" label="价格" width="180" />
      <el-table-column prop="discount" label="折扣">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.discount"
                :step="0.1"
                :min="0"
                :max="1"
                @change="changeDiscount(scope.row)"
              ></el-input-number>
            </template>
          </el-table-column>
      <el-table-column prop="foodTypeName" label="菜品类型" width="180" />
      <el-table-column prop="storeProductState" label="是否下架" width="180">
        <template #default="scope">
          <el-switch
            v-model="scope.row.storeProductState"
            :active-value="1"
            :inactive-value="0"
            @change="handleSwitchChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="showEditDialog(scope.row)">修改</el-button>
          <el-button size="small"  @click="showImageDialog(scope.row)">修改图片</el-button>
          <el-button size="small" type="danger" @click="deleteProduct(scope.row.storeProductId)">删除</el-button>
          
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
          background
          layout="prev, pager, next, sizes, total"
          :total="total"
          :page-size="searchParam.pageSize"
          :current-page="searchParam.pageNum"
          :page-sizes="[2, 3, 5, 10]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  
    <!-- 编辑模态框 -->
    <el-dialog
    v-model="editVisible"
    title="编辑商品"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
>
  <el-form :model="currentProduct" label-width="100px" :rules="rules" ref="editForm">
    <el-form-item label="名称" prop="productName">
      <el-input v-model="currentProduct.productName" />
    </el-form-item>
    <el-form-item label="价格" prop="price">
      <el-input v-model="currentProduct.price" />
    </el-form-item>
    <el-form-item label="菜品类型" prop="foodTypeName">
      <el-select v-model="currentProduct.foodTypeId" placeholder="请选择菜品类型">
        <el-option
            v-for="type in foodTypes"
            :key="type.foodTypeId"
            :label="type.foodTypeName"
            :value="type.foodTypeId"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="菜品介绍" prop="productIntr">
      <el-input
          v-model="currentProduct.productIntr"
          type="textarea"
          :rows="4"
          placeholder="请输入菜品介绍"
      />
    </el-form-item>
  </el-form>
  <template #footer>
    <span style="position: relative; left: -900px;">
      <el-button @click="editVisible = false">取消</el-button>
      <el-button type="primary" @click="handleEditSubmit">保存</el-button>
      
    </span>
  </template>
</el-dialog>
  </div>
</template>

<script>
import { ElInput, ElButton, ElTable, ElTableColumn, ElPagination, ElDialog, ElForm, ElFormItem, ElSwitch, ElMessage } from 'element-plus';
import axios from 'axios';
export default {
  components: {
    ElInput,
    ElButton,
    ElTable,
    ElTableColumn,
    ElPagination,
    ElDialog,
    ElForm,
    ElFormItem,
    ElSwitch,
  },data() {
  return {
    products: [],
    searchParam: {
      storeId: localStorage.getItem("storeId"),
      pageNum: 1,
      pageSize: 5
    },
    foodTypes: [], // 食物类型列表
    total: 0,
    detailVisible: false, // 控制详情模态框显示
    editVisible: false, // 控制编辑模态框显示
    currentProduct: {
      storeProductId: '',
      productName: '',
      price: '',
      foodTypeId: '',
      productIntr: '' // 新增菜品介绍字段
    },
    rules: {
      productName: [
        { required: true, message: '请输入商品名称', trigger: 'blur' }
      ],
      price: [
        { required: true, message: '请输入商品价格', trigger: 'blur' },
        { pattern: /^\d+(\.\d{1,2})?$/, message: '价格必须是两位小数且大于0的数字', trigger: 'blur' }
      ],
      foodTypeName: [
        { required: true, message: '请选择菜品类型', trigger: 'change' }
      ],
      dishDesc: [
        { required: true, message: '请输入菜品介绍', trigger: 'blur' }
      ]
    },
  };
},
  methods:{
    deleteProduct(id) {
      
      this.$confirm('确定要删除该用户吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        this.$message.success('删除成功');
        // 执行删除操作的逻辑
        this.products = this.products.filter(product => product.storeProductId !== id);
      axios.delete('/meals/storeProduct/deleteProduct', {
        params: { productId: id }
      }).then(res => {
        if (res.data.code === 200) {
          this.getProducts();
          ElMessage.success('删除成功');
        } else {
          ElMessage.error(res.data.msg);
        }
      });
      })
      .catch(() => {
        this.$message.info('已取消删除');
      });

     
      
    },    
    changeDiscount(row){
        const product={
          storeProductId:row.storeProductId,
          discount:row.discount
        };
        axios.post("/meals/storeProduct/updateDiscount",product
      ).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg);
          this.getProducts();
        }else{
          ElMessage.error(res.data.msg);
        }
      })
      },
    handleFileChange(file) {
      this.fileUpload = file.raw;
    },
    getProducts() {
      axios.post('/meals/storeProduct/searchStoreProductList', this.searchParam).then(res => {
        if (res.data.code === 200) {
          this.products = res.data.data.list;
          this.total = res.data.data.total;
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    },
    getFoodTypes() {
      axios.get('/meals/foodType/searchType', {
        params: {storeId: localStorage.getItem("storeId")}
      }).then(res => {
        if (res.data.code === 200) {
          this.foodTypes = res.data.data;
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    },
    showDetail(product) {
      this.currentProduct = product; // 设置当前商品详情
      this.detailVisible = true; // 显示模态框
    },
    showEditDialog(product) {
      this.currentProduct = { ...product }; // 复制当前商品信息
      this.editVisible = true; // 显示编辑模态框
    },
    handleEditSubmit() {
      console.log(this.currentProduct);
    this.$refs.editForm.validate((valid) => {
      if (valid) {
        // 提交编辑逻辑
        axios.post('/meals/storeProduct/updateStoreProduct', this.currentProduct).then(res => {
          if (res.data.code === 200) {
            ElMessage.success('商品信息更新成功');
            this.editVisible = false;
            this.getProducts(); // 刷新商品列表
          } else {
            ElMessage.error(res.data.msg);
          }
        });
      } else {
        ElMessage.error('请填写完整信息');
      }
    });
  },
    handleSwitchChange(product) {
      if(product.storeProductState===0){
        axios.get('/meals/storeProduct/putOn', {
          params:{
            productId: product.storeProductId
          }
          
        }).then(res => {
          if (res.data.code === 200) {
            ElMessage.success('商品状态切换成功');
          } else {
            ElMessage.error(res.data.msg);
          }
        });
     }else if(product.storeProductState===1){
        axios.get('/meals/storeProduct/putOff', {
          params:{
            productId: product.storeProductId
          }
        }).then(res => {
          if (res.data.code === 200) {
            ElMessage.success('商品状态切换成功');
          } else {
            ElMessage.error(res.data.msg);
          }
        });
      }
    },
    handleSizeChange(newSize) {
      this.searchParam.pageSize = newSize;
      this.searchParam.pageNum = 1; // 重置到第一页
      this.getProducts();
    },
    handleCurrentChange(newPage) {
      this.searchParam.pageNum = newPage;
      this.getProducts();
    },
  },
  created() {
    this.getProducts();
    this.getFoodTypes();
  }
};
</script>

<style scoped>

.product-list {
  margin: 20px;
  font-family: Arial, sans-serif;
}

h1 {
  color: #333;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}




</style>